//
//  MainViewController.swift
//  ZJWeiBo
//
//  Created by 张建 on 2018/3/18.
//  Copyright © 2018年 micheal. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        
        super.viewDidLoad()
        tabBar.tintColor = UIColor.lightGray
        
        let configArray = loadConfigArray()
        //遍历数组创建控制器
        for dic in configArray! {
            
            addChildViewController(childViewControllerName: dic["vcName"]!, title: dic["title"]!, imageName: dic["imageName"]!)
        }
    }
    
    
    /// 添加主控制器
    ///
    /// - Parameters:
    ///   - childViewControllerName: 控制器名称
    ///   - title: 模块名称
    ///   - imageName: 模块图标
    private func addChildViewController(childViewControllerName:String, title:String, imageName:String) {
        
        //根据字符串动态创建类
        /**
         1. 动态获取命名空间
         2. 通过类创建对象
        */
        let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
        let cls: AnyClass? = NSClassFromString(nameSpace+"."+childViewControllerName)
        let vcCls = cls as! UIViewController.Type
        let vc = vcCls.init()
        // 设置
        vc.navigationItem.title = title
        vc.tabBarItem.title = title
        vc.tabBarItem.image = UIImage(named:imageName)
        vc.tabBarItem.selectedImage = UIImage(named:imageName+"_highlighted")
        let homeNavi = UINavigationController(rootViewController: vc)
        addChildViewController(homeNavi)
        
    }
    
    
    
    /// 获取tabbar配置数组
    ///
    /// - Returns: 返回配置数组
    private func loadConfigArray() ->[[String:String]]? {
        
        //读取tabbar配置数据
        let configPath = Bundle.main.path(forResource: "tabBarConfig.json", ofType: nil)
        if let theConfigPath = configPath {
            let configData = NSData(contentsOfFile: theConfigPath)
            if let theconfigData = configData {
                
                do
                {
                    let configArr = try JSONSerialization.jsonObject(with: theconfigData as Data, options: .mutableContainers)
                    return configArr as? [[String : String]]
                    
                }
                catch{
                    //异常处理
                    return nil
                }
                
            }
        }
        return nil
    }
}

